package com.capsulode.excel.conversion.impl;

import com.capsulode.excel.conversion.Converter;
import com.capsulode.excel.exception.CellTypeNotExpectException;
import com.capsulode.excel.exception.ConversionFailException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;

public class BooleanConverter implements Converter<Boolean> {
    @Override
    public Boolean convert(Cell cell) throws IllegalStateException, CellTypeNotExpectException {
        if (CellType.BOOLEAN.equals(cell.getCellTypeEnum())) {
            return cell.getBooleanCellValue();
        }
        if (CellType.BLANK.equals(cell.getCellTypeEnum())) {
            //空输入，使用默认值
            return null;
        }
        if (CellType.NUMERIC.equals(cell.getCellTypeEnum())) {
            return cell.getNumericCellValue() == 1;
        }
        if (CellType.STRING.equals(cell.getCellTypeEnum())) {
            String s = cell.getStringCellValue();
            if (s.isEmpty()) {
                return null;
            }
            return "true".equalsIgnoreCase(s)
                    || "yes".equalsIgnoreCase(s)
                    || "on".equalsIgnoreCase(s)
                    || "success".equalsIgnoreCase(s)
                    || "1".equals(s);
        }
        throw new CellTypeNotExpectException(cell.getRowIndex(), cell.getColumnIndex());
    }

    @Override
    public void serialize(Object value, Cell cell) throws ConversionFailException, CellTypeNotExpectException {
        if (value instanceof Boolean) {
            cell.setCellValue((Boolean) value);
            return;
        }
        if (value instanceof Number) {
            cell.setCellValue(1 == ((Number) value).intValue());
            return;
        }
        if (value instanceof CharSequence) {
            String s = value.toString();
            boolean val = "true".equalsIgnoreCase(s)
                    || "yes".equalsIgnoreCase(s)
                    || "on".equalsIgnoreCase(s)
                    || "success".equalsIgnoreCase(s)
                    || "1".equals(s);
            cell.setCellValue(val);
            return;
        }
        throw new CellTypeNotExpectException(cell.getRowIndex(), cell.getColumnIndex());
    }
}
